package com.lnking.lnkingplace.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lnking.common.http.ReturnResult;
import com.lnking.lnkingplace.Util.LocalDateTimeUtil;
import com.lnking.lnkingplace.Util.QrcodeUtil;
import com.lnking.lnkingplace.Util.UserUtil;
import com.lnking.lnkingplace.mapper.PwdLogMapper;
import com.lnking.lnkingplace.mapper.UserMapper;
import com.lnking.lnkingplace.model.dto.isolation.room.RoomDetailImport;
import com.lnking.lnkingplace.model.dto.user.UserDetailDto;
import com.lnking.lnkingplace.model.dto.user.UserDto;
import com.lnking.lnkingplace.model.dto.user.UserImportDto;
import com.lnking.lnkingplace.model.entity.*;
import com.lnking.lnkingplace.model.enums.DateFormat;
import com.lnking.lnkingplace.model.enums.UserType;
import com.lnking.lnkingplace.model.request.user.UpdatePasswordRequest;
import com.lnking.lnkingplace.model.request.user.UserAddRequest;
import com.lnking.lnkingplace.model.request.user.UserSearchRequest;
import com.lnking.lnkingplace.service.*;
import com.lnking.starter.export.utils.ImportOption;
import com.lnking.starter.export.utils.ImportUtils;
import com.lnking.starter.mybatis.entity.BaseEntity;
import com.lnking.starter.mybatis.service.impl.CustomServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zxq
 * @since 2022-08-18
 */
@Service
public class UserServiceImpl extends CustomServiceImpl<UserMapper, User> implements IUserService {

    /**
     * 核酸状态标识
     */
    // 已超时
    public static final String RED="red";
    // 提醒
    public static final String ORANGE="orange";
    // 安全
    public static final String GREEN="green";
    // 暂无核酸信息
    public static final String BLANK="blank";

    public static final String TYPE = "从业人员";

    @Resource
    IPlaceInfoService placeInfoService;

    @Autowired
    UserUtil userUtil;

    @Autowired
    INucleicAcidSetService  nucleicAcidSetService;

    @Autowired
    IRecordUserService recordUserService;

    @Autowired
    ILeadersService leadersService;

    @Resource
    PwdLogMapper pwdLogMapper;

    @Autowired
    IIsolationPersonnelService isolationPersonnelService;

    @Resource
    IIsolationWorkerService iIsolationWorkerService;

    @Resource
    QrcodeUtil qrcodeUtil;

    public static final String  PWD ="123456";

    @Override
    public User getUserByName(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getPhone, username);
        return getBaseMapper().selectOne(wrapper);
    }

    @Override
    public UserDetailDto getUserDetailById(String id) {
        return getBaseMapper().getDetailById(id);
    }

    @Override
    public void add(UserAddRequest params) throws Exception {
        // 防止重复
        QueryWrapper<User> wapper = new QueryWrapper<>();
        wapper.lambda().eq(User::getPhone, params.getPhone());
        Integer integer = getBaseMapper().selectCount(wapper);
        Assert.isTrue(integer == 0, "手机号码不能重复");
        User user = new User();
        BeanUtils.copyProperties(params, user);
        if (user.getEntryTime()!= null) {
            user.setEntryTime(params.getEntryTime().toLocalDate());
        }
        // 获取上级的渠道
        UserDto user1 = userUtil.getUser();
        user.setChannel(user1.getChannel());
        user.setCreatorTime(LocalDateTime.now());
        user.setPassword( DigestUtils.sha1Hex(PWD));
        user.setQrcode(qrcodeUtil.getQrCodeById(user.getId()));
        getBaseMapper().insert(user);

    }

    @Override
    public void delById(String id) throws Exception {
        User user = getBaseMapper().selectById(id);
        UserDto dto = userUtil.getUser();
        // 不能删除自己
        if (dto.getId().equals(user.getId())){
            throw new Exception("场所负责人无法删除本人信息");
        }
        // 如果删除人员是场所负责人
        if (user.getType().equals(UserType.LOCATION)) {
            throw new Exception("场所负责人不能被删除");
            // 更新场所信息
//            if(null != user.getPlaceId()){
//                PlaceInfo placeInfo = placeInfoService.getBaseMapper().selectById(user.getPlaceId());
//                placeInfo.setLinkman(null);
//                placeInfo.setLinkmanPhone(null);
//                placeInfoService.updateById(placeInfo);
//            }
        }
        removeById(id);

    }

    @Override
    public Object getPageList(UserSearchRequest params) {
        // List<UserDto> userDtoList = (List<UserDto>) pageList(params);
        /*// 1. 获取当前登录人的核酸配置
        UserDto user = userUtil.getUser();
        NucleicAcidSet nucleicAcidSet = nucleicAcidSetService.find(user.getId());
        // 暗橘色配置 配置时间前一天
        // 提醒时间
        LocalDateTime remindTime = LocalDateTime.now().minusDays(nucleicAcidSet.getType()-1);
        // 超过时间
        LocalDateTime outTime = LocalDateTime.now().minusDays(nucleicAcidSet.getType());
        // 2. 判断是否超过，超过标记红色，没超过标记暗橘色
        userDtoList.forEach(e->{
            if (e.getResultTime() == null) {
                e.setStatus(BLANK);
            } else {
                // 在提示时间之后，安全
                if (e.getResultTime().isAfter(remindTime)) {
                    e.setStatus(GREEN);
                } else {
                    // 在超时时间后 ，超时提示
                    if (e.getResultTime().isBefore(outTime)) {
                        e.setStatus(RED);
                    } else {
                        // 在之间 提示该核酸
                        e.setStatus(ORANGE);
                    }
                }
            }
        });*/
        return pageList(params);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePwd(UpdatePasswordRequest params) {
        UserDto user1 = userUtil.getUser();
        User userEntity = this.getById(user1.getId());
        if (userEntity == null) {
            Leaders leader = leadersService.getById(user1.getId());
            if(leader != null){
                Assert.isTrue(DigestUtils.sha1Hex(params.getOldPassword()).equals(leader.getPassword()), "原密码不正确");
                Leaders leaders = new Leaders();
                leaders.setId(user1.getId());
                leaders.setPassword(DigestUtils.sha1Hex(params.getNewPassword()));
                leadersService.updateById(leaders);
            }else{
                IsolationPersonnel isolationByName = isolationPersonnelService.getById(user1.getId());
                if(isolationByName !=null){
                    Assert.isTrue(DigestUtils.sha1Hex(params.getOldPassword()).equals(isolationByName.getPassword()), "原密码不正确");
                    IsolationPersonnel isolationPersonnel = new IsolationPersonnel();
                    isolationPersonnel.setId(user1.getId());
                    isolationPersonnel.setPassword(DigestUtils.sha1Hex(params.getNewPassword()));
                    isolationPersonnelService.updateById(isolationPersonnel);
                }else{
                    IsolationWorker isolationWorker = iIsolationWorkerService.getById(user1.getId());
                    if(isolationWorker !=null){
                        Assert.isTrue(DigestUtils.sha1Hex(params.getOldPassword()).equals(isolationWorker.getPassword()), "原密码不正确");
                        IsolationWorker worker = new IsolationWorker();
                        worker.setId(user1.getId());
                        worker.setPassword(DigestUtils.sha1Hex(params.getNewPassword()));
                        iIsolationWorkerService.updateById(worker);
                    }
                }

            }
        } else {
            Assert.isTrue(DigestUtils.sha1Hex(params.getOldPassword()).equals(userEntity.getPassword()), "原密码不正确");
            User user = new User();
            user.setId(user1.getId());
            user.setPassword(DigestUtils.sha1Hex(params.getNewPassword()));
            this.updateById(user);
        }

        //记录日志
        PwdLog pl = new PwdLog();
        pl.setNewPwd(params.getNewPassword());
        pl.setOperator(userUtil.getUser().getName());
        pl.setOperatorPhone(userUtil.getUser().getPhone());
        pl.setOperatorTime(LocalDateTime.now());
        pwdLogMapper.insert(pl);
    }

    @Override
    public List<User> personList(String name) {
        UserDto user = userUtil.getUser();
        QueryWrapper<User> swapper = new QueryWrapper<>();
        if(name!=null){
            swapper.lambda().eq(User::getName,name);
        }
        swapper.lambda().eq(User::getPlaceId,user.getPlaceId());
        swapper.lambda().eq(User::getType,TYPE);
       return list(swapper);
    }

    @Override
    public List<User> findByIdCard(String idCardNo) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getIdCard, idCardNo);
        return getBaseMapper().selectList(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importExcel(MultipartFile file) throws Exception {
        ImportOption option = new ImportOption.Builder().build();
        List<UserImportDto> result =  ImportUtils.importExcel(file, UserImportDto.class,option);
        for (UserImportDto userImportDto : result.stream().filter(e->e.getName()!=null).collect(Collectors.toList())) {
            userImportDto.setIdCard(userImportDto.getIdCard().trim());
            userImportDto.setName(userImportDto.getName().trim());
            userImportDto.setPhone(userImportDto.getPhone().trim());
            // place
            PlaceInfo check = placeInfoService.check(userImportDto.getPlaceName());
            String placeId=null;
            if(check == null){
                PlaceInfo placeInfo = new PlaceInfo();
                BeanUtils.copyProperties(userImportDto,placeInfo);
                placeInfo.setCreateTime(LocalDateTime.now());
                placeInfo.setChannel("文创局");
                placeInfo.setAuditTime(LocalDateTime.now());
                placeInfoService.save(placeInfo);
                placeId=placeInfo.getId();
            }else{
                placeId=check.getId();
            }
            // user
            User userByName = getUserByName(userImportDto.getPhone());
            if(userByName ==null){
                User user =new User();
                user.setPhone(userImportDto.getPhone());
                user.setName(userImportDto.getName());
                user.setPlaceId(placeId);
                user.setChannel("文创局");
                user.setIdCard(userImportDto.getIdCard());
                save(user);
            }
        }
    }


    // 传入手机号 写入验证码
    @Override
    public void findPhone(String phone) {
        // 行业人员
        User user = getUserByName(phone);
        if (user == null) {
            // 从监管里面查询
            Leaders leader = leadersService.getLeaderByName(phone);
            if(leader ==null){
                // 隔离人员登录
                IsolationPersonnel isolationByName = isolationPersonnelService.getIsolationByName(phone);
                if(isolationByName==null){
                    // 一线人员
                    IsolationWorker workeByName = iIsolationWorkerService.getWorkeByName(phone);
                        Assert.notNull(workeByName, ReturnResult.ResultStatus.USERNAME_NOT_FOUND.getDesc());
                }

            }
        }
    }
}
